<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity
{
	private $_id;

	// admins can login by setting this value to true to passby password checking
	public $adminLogin = false;
	
	/*
	* Authenticates a user.
	* NOTICE: Constructor receive email for 1st param under variable named $username
	* @return boolean whether authentication succeeds.
	*/
	public function authenticate()
	{
		$criteria=new CDbCriteria;
		$criteria->select = array('id','name','email','password','username');
		$criteria->condition='email=:email';
		$criteria->params=array(':email'=>$this->username);
		$criteria->limit = 1;
		
		$usermodel=User::model()->find($criteria);

		// username is exist
		if($usermodel === NULL) {
			$this->errorCode=self::ERROR_PASSWORD_INVALID;
		} else {
			if($this->adminLogin || $usermodel->checkPassword($this->password)) {
				$this->_id = $usermodel->id;
				$this->username = $usermodel->username;
				Yii::app()->user->setState('name',$usermodel->name);
				Yii::app()->user->setState('email',$usermodel->email);
				
				$session = new CHttpSession;
				$session->open();
				$session['isLoggedIn'] = true;
				$session['user'] = $usermodel->username;

				// Override any config option
				$session['imagemanager.filesystem.rootpath'] = Yii::app()->basePath .'/../upload/tinymce/';
				$session['imagemanager.filesystem.path'] = Yii::app()->basePath .'/../upload/';
				
				$this->errorCode=self::ERROR_NONE;
			} else {
				$this->errorCode=self::ERROR_PASSWORD_INVALID;
			}
		}

		return !$this->errorCode;
	}
	
	public function getId()
	{
		return $this->_id;
	}
}